package com.control.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.control.api.Gb28181Api;
import com.control.api.MediaApi;
import com.control.api.OnvifApi;
import com.control.commons.ApiCodeEnum;
import com.control.commons.ApiResult;
import com.control.db.entity.BrandEntity;
import com.control.db.entity.CameraEntity;
import com.control.db.entity.RecordEntity;
import com.control.db.service.BrandService;
import com.control.db.service.CameraService;
import com.control.db.service.RecordService;

@RestController
@RequestMapping("/media")
public class MediaControlController {
	@Autowired
	Gb28181Api gb28181Api;
	@Value("${media.server-ip}")
	String mediaIp;
	@Value("${media.stream-port}")
	String mediaStreamPort;
	@Value("${gb28181.live-url}")
	String gb28181LiveUrl;
	@Value("${rtsp.live-url}")
	String rtspLiveUrl;
	@Value("${onvif.live-url}")
	String onvifLiveUrl;
	@Autowired
	MediaApi mediaApi;
	@Autowired
	CameraService cameraService;
	@Autowired
	BrandService brandService;
	@Autowired
	RecordService recordService;
	@Value("${media.secret}")
	String mediaSecret;
	@Autowired
	OnvifApi onvifApi;

	/***
	 * 摄像机列表
	 */
	@GetMapping("/list")
	public ApiResult list() {
		CameraEntity cp = new CameraEntity();
		List<CameraEntity> cameraList = cameraService.listAll(cp);
		return new ApiResult(ApiCodeEnum.OK,cameraList);
	}
	@GetMapping("/saveOrUpdate")
	public ApiResult saveOrUpdate(CameraEntity c) {
		CameraEntity result = cameraService.saveOrUpdate(c);
		return new ApiResult(ApiCodeEnum.OK,result);
	}
	@GetMapping("/delete")
	public ApiResult delete(CameraEntity c) {
		cameraService.delete(c);
		return new ApiResult(ApiCodeEnum.OK);
	}
	@GetMapping("/findOne")
	public ApiResult findOne(CameraEntity c) {
		CameraEntity result = cameraService.findOne(c);
		if(result!=null) {
			return new ApiResult(ApiCodeEnum.OK,result);
		} else {
			return new ApiResult(ApiCodeEnum.INVALID_REQUEST);
		}
	}
	/***
	 * 请求直播
	 *type
	 *1-gb28181
	 *2-onvif
	 *3-rtsp
	 */
	@GetMapping("/live/{deviceId}_{channelId}")
	public ApiResult live(@PathVariable String deviceId,@PathVariable String channelId) {
		CameraEntity cp = new CameraEntity();
		cp.setDeviceId(deviceId);
		cp.setChannelId(channelId);
		CameraEntity c1 = cameraService.findOne(cp);
		if(c1==null) {
			return new ApiResult(ApiCodeEnum.INVALID_REQUEST);
		}
		switch (c1.getType()) {
			case 1:
				//gb28181
				if(c1.getLiveStatus()==1) {
					//播放中
					String liveGb28181Url = gb28181LiveUrl.replace("{mediaIp}", mediaIp).replace("{mediaStreamPort}", mediaStreamPort).replace("{liveKey}", c1.getLiveKey()).replace("{secret}", mediaSecret);
					return new ApiResult(ApiCodeEnum.OK,(Object)liveGb28181Url);
				} else {
					//未播放
					String nSsrc = "0"+gb28181Api.live(deviceId, channelId);
					if(!nSsrc.equals("0")) {
						c1.setLiveKey(nSsrc);
						c1.setLiveStatus(1);
						cameraService.saveOrUpdate(c1);
						String liveGb28181Url = gb28181LiveUrl.replace("{mediaIp}", mediaIp).replace("{mediaStreamPort}", mediaStreamPort).replace("{liveKey}", nSsrc).replace("{secret}", mediaSecret);
						return new ApiResult(ApiCodeEnum.OK,(Object)liveGb28181Url);
					} else {
						return new ApiResult(ApiCodeEnum.SERVER_ERROR);
					}
				}
			case 2:
				if(c1.getLiveStatus()==1) {
					String liveOnvifUrl = onvifLiveUrl.replace("{mediaIp}", mediaIp).replace("{mediaStreamPort}", mediaStreamPort).replace("{liveKey}", c1.getLiveKey()).replace("{secret}", mediaSecret);
					return new ApiResult(ApiCodeEnum.OK,(Object)liveOnvifUrl);
				} else {
					String onvifUrl = onvifApi.live(deviceId, channelId);
					String onvifKey = c1.getDeviceId()+"_"+c1.getChannelId();
					Boolean res = mediaApi.addStreamProxy(onvifKey, onvifUrl);
					if(res) {
						c1.setLiveKey(onvifKey);
						c1.setLiveStatus(1);
						cameraService.saveOrUpdate(c1);
						String liveOnvifUrl = onvifLiveUrl.replace("{mediaIp}", mediaIp).replace("{mediaStreamPort}", mediaStreamPort).replace("{liveKey}", c1.getLiveKey()).replace("{secret}", mediaSecret);
						return new ApiResult(ApiCodeEnum.OK,(Object)liveOnvifUrl);
					} else {
						return new ApiResult(ApiCodeEnum.SERVER_ERROR);
					}
				}
			case 3:
				//rtsp
				if(c1.getLiveStatus()==1) {
					//播放中
					String liveRtspUrl = rtspLiveUrl.replace("{mediaIp}", mediaIp).replace("{mediaStreamPort}", mediaStreamPort).replace("{liveKey}", c1.getLiveKey()).replace("{secret}", mediaSecret);
					return new ApiResult(ApiCodeEnum.OK,(Object)liveRtspUrl);
				} else {
					//未播放
					BrandEntity bp = new BrandEntity();
					bp.setId(c1.getBrandId());
					BrandEntity rb = brandService.findOne(bp);
					String rtspUrl = rb.getRtspUrl();
					String uRtspUrl = rtspUrl.replace("{username}", c1.getUsername()).replace("{password}", c1.getPassword()).replace("{ip}", c1.getIp()).replace("{rtspPort}", c1.getRtspPort().toString()).replace("{rtspChannel}", c1.getRtspChannel());
					String rtspKey = c1.getDeviceId()+"_"+c1.getChannelId();
					Boolean res = mediaApi.addStreamProxy(rtspKey, uRtspUrl);
					if(res) {
						c1.setLiveKey(rtspKey);
						c1.setLiveStatus(1);
						cameraService.saveOrUpdate(c1);
						String liveRtspUrl = rtspLiveUrl.replace("{mediaIp}", mediaIp).replace("{mediaStreamPort}", mediaStreamPort).replace("{liveKey}", c1.getLiveKey()).replace("{secret}", mediaSecret);
						return new ApiResult(ApiCodeEnum.OK,(Object)liveRtspUrl);
					} else {
						return new ApiResult(ApiCodeEnum.SERVER_ERROR);
					}
				}
			default:
				return new ApiResult(ApiCodeEnum.INVALID_REQUEST);
		}
	}
	/***
	 * 云台控制
	 */
	@GetMapping("/ptz/{deviceId}_{channelId}")
	public ApiResult ptz(@PathVariable String deviceId,@PathVariable String channelId,int leftRight, int upDown, int inOut, int moveSpeed, int zoomSpeed) {
		CameraEntity cp = new CameraEntity();
		cp.setDeviceId(deviceId);
		cp.setChannelId(channelId);
		CameraEntity c1 = cameraService.findOne(cp);
		if(c1==null) {
			return new ApiResult(ApiCodeEnum.INVALID_REQUEST);
		}
		switch (c1.getType()) {
			case 1:
				Boolean result = gb28181Api.ptz(deviceId, channelId, leftRight, upDown, inOut, moveSpeed, zoomSpeed);
				if(result) {
					return new ApiResult(ApiCodeEnum.OK);
				} else {
					return new ApiResult(ApiCodeEnum.INVALID_REQUEST);
				}
			case 2:
				Boolean result1 = onvifApi.ptz(deviceId, channelId, leftRight, upDown, inOut);
				if(result1) {
					return new ApiResult(ApiCodeEnum.OK);
				} else {
					return new ApiResult(ApiCodeEnum.INVALID_REQUEST);
				}
			case 3:
				return new ApiResult(ApiCodeEnum.INVALID_REQUEST,"RTSP协议不支持云台控制");
			default:
				return new ApiResult(ApiCodeEnum.INVALID_REQUEST);
		}
	}
	/***
	 * 本地录制
	 * @return
	 */
	@GetMapping("/lRecord/start/{deviceId}_{channelId}")
	public ApiResult lRecordStart(@PathVariable String deviceId,@PathVariable String channelId) {
		CameraEntity cp = new CameraEntity();
		cp.setDeviceId(deviceId);
		cp.setChannelId(channelId);
		CameraEntity c1 = cameraService.findOne(cp);
		if(c1==null) {
			return new ApiResult(ApiCodeEnum.INVALID_REQUEST);
		}
		if(c1.getRecordStatus() == 1) {
			//录制中
			return new ApiResult(ApiCodeEnum.OK);
		} else {
			//未录制 开启录制
			//查看是否有人在看直播
			if(c1.getLiveKey()!=null && c1.getLiveStatus()==1) {
				Boolean resR = mediaApi.startRecord(c1);
				if(resR) {
					c1.setRecordStatus(1);
					cameraService.saveOrUpdate(c1);
				}
				return new ApiResult(ApiCodeEnum.OK);
			} else {
				switch (c1.getType()) {
					case 1:
						//开启直播
						String nSsrc = gb28181Api.live(deviceId, channelId);
						c1.setLiveKey(nSsrc);
						c1.setLiveStatus(1);
						cameraService.saveOrUpdate(c1);
						Boolean resR = mediaApi.startRecord(c1);
						if(resR) {
							c1.setRecordStatus(1);
							cameraService.saveOrUpdate(c1);
						}
						return new ApiResult(ApiCodeEnum.OK);
					case 3:
						//未播放
						BrandEntity bp = new BrandEntity();
						bp.setId(c1.getBrandId());
						BrandEntity rb = brandService.findOne(bp);
						String uRtspUrl = rb.getRtspUrl().replace("{username}", c1.getUsername()).replace("{password}", c1.getPassword()).replace("{ip}", c1.getIp()).replace("{rtspPort}", c1.getRtspPort().toString()).replace("{rtspChannel}", c1.getRtspChannel());
						String rtspKey = c1.getDeviceId()+"_"+c1.getChannelId();
						Boolean res = mediaApi.addStreamProxy(rtspKey, uRtspUrl);
						c1.setLiveKey(rtspKey);
						c1.setLiveStatus(1);
						cameraService.saveOrUpdate(c1);
						Boolean resR1 = mediaApi.startRecord(c1);
						if(resR1) {
							c1.setRecordStatus(1);
							cameraService.saveOrUpdate(c1);
						}
						return new ApiResult(ApiCodeEnum.OK);
					default:
						return new ApiResult(ApiCodeEnum.INVALID_REQUEST);
				}
			}
		}
	}
	/***
	 * 结束本地录制
	 * @return
	 */
	@GetMapping("/lRecord/stop/{deviceId}_{channelId}")
	public ApiResult lRecordStop(@PathVariable String deviceId,@PathVariable String channelId) {
		CameraEntity cp = new CameraEntity();
		cp.setDeviceId(deviceId);
		cp.setChannelId(channelId);
		CameraEntity c1 = cameraService.findOne(cp);
		if(c1==null) {
			return new ApiResult(ApiCodeEnum.INVALID_REQUEST);
		}
		if(c1.getRecordStatus() == 1) {
			//录制中 结束
			if(c1.getLiveKey()!=null) {
				Boolean resR = mediaApi.stopRecord(c1);
				if(resR) {
					c1.setRecordStatus(0);
					cameraService.saveOrUpdate(c1);
				}
			}
			return new ApiResult(ApiCodeEnum.OK);
		} else {
			return new ApiResult(ApiCodeEnum.OK,"未录制");
		}
	}
	/***
	 * 本地回放列表
	 */
	@GetMapping("/lReplayList/{deviceId}_{channelId}")
	public ApiResult lReplayList(@PathVariable String deviceId,@PathVariable String channelId) {
		RecordEntity rp = new RecordEntity();
		rp.setChannelId(channelId);
		rp.setDeviceId(deviceId);
		List<RecordEntity> rlist = recordService.listAll(rp);
		return new ApiResult(ApiCodeEnum.OK,rlist);
	}
}
